<template>
    <div class="app-container">
        <!-- 查询表单 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true">
            <el-form-item label="编码" prop="productSn">
                <el-input v-model="queryParams.productSn" placeholder="请输入编码" clearable style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="名称" prop="productName">
                <el-input v-model="queryParams.productName" placeholder="请输入名称" clearable style="width: 200px"
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类别" prop="productCategoryId">
                <el-select v-model="queryParams.productCategoryId" style="width: 200px" placeholder="请选择类别">
                    <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
                        :value="item.categoryId" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">批量删除</el-button>
            </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-table :data="productList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="ID" prop="productId" />
            <el-table-column label="编码" prop="productSn" />
            <el-table-column label="名称" prop="productName" />
            <el-table-column label="类别ID" prop="productCategoryId" />
            <el-table-column label="类别" prop="category.categoryName" />
            <el-table-column label="价格" prop="price" />
            <el-table-column label="图片" prop="imageUrl">
                <template #default="scope">
                    <el-image :src="scope.row.imageUrl" style="width: 100px; height: 100px;" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                    <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination style="margin-top: 20px;" :total="total" v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize" :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" @size-change="getList" @current-change="getList" />

        <!-- 新增/修改对话框 -->
        <el-dialog v-model="dialogOpen" :title="title" width="600px">
            <ProductForm v-if="dialogOpen" :product-id="productId" />
        </el-dialog>

        <!-- 查看抽屉 -->
        <el-drawer v-model="drawerOpen" title="查看商品数据" direction="rtl" size="50%">
            <el-descriptions :column="2" border>
                <el-descriptions-item label="编码">{{ currentProduct?.productSn }}</el-descriptions-item>
                <el-descriptions-item label="名称">{{ currentProduct?.productName }}</el-descriptions-item>
                <el-descriptions-item label="价格">{{ currentProduct?.price }}</el-descriptions-item>
                <el-descriptions-item label="类别">{{ currentProduct?.category?.categoryName }}</el-descriptions-item>
                <el-descriptions-item label="描述">{{ currentProduct?.productDescription }}</el-descriptions-item>
            </el-descriptions>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { listProduct, getProduct } from '@/api/product'
import { listCategory } from '@/api/category'
import ProductForm from '@/components/ProductForm.vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'

// =========== 定义接口 ===========
interface Product {
    productId: number
    productSn: string
    productName: string
    productDescription: string
    price: number
    productCategoryId: number
    category: {
        categoryId: number
        categoryName: string
    }
    imageUrl: string
    detailUrl: string
}

interface Category {
    categoryId: number
    categoryName: string
}

// =========== 定义响应式数据 ===========
const productList = ref<Product[]>([])
const dialogOpen = ref(false)
const drawerOpen = ref(false)
const title = ref('')
const ids = ref<number[]>([])
const productId = ref(0)
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const queryRef = ref<FormInstance | null>(null)
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    productSn: '',
    productName: '',
    productCategoryId: null,
})
const categoryOptions = ref<Category[]>([])
const currentProduct = ref<Product | null>(null)

// =========== 生命周期钩子 ===========
onMounted(() => {
    getList()
    getCategoryList()
})

// =========== 方法 ===========
/** 获取商品列表 */
function getList() {
    listProduct(queryParams).then((res) => {
        if (res.data && (res.data.list || res.data.rows || res.data.records)) {
            productList.value = res.data.list || res.data.rows || res.data.records;
            total.value = res.data.total;
        } else if (Array.isArray(res.data)) {
            const allData = res.data;
            total.value = allData.length;
            const currentPage = queryParams.pageNum;
            const pageSize = queryParams.pageSize;
            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            productList.value = allData.slice(start, end);
        } else {
            productList.value = [];
            total.value = 0;
        }
    })
}

/** 获取类别列表 */
function getCategoryList() {
    listCategory().then((res) => {
        categoryOptions.value = res.data
    })
}

/** 处理查询 */
function handleQuery() {
    queryParams.pageNum = 1
    getList()
}

/** 重置查询 */
function resetQuery() {
    if (!queryRef.value) return
    queryRef.value.resetFields()
    getList()
}

/** 处理表格选中事件 */
function handleSelectionChange(selection: Product[]) {
    ids.value = selection.map((item) => item.productId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    dialogOpen.value = true
    title.value = '新增商品'
}

/** 修改按钮操作 */
function handleUpdate(row: Product) {
    productId.value = row.productId
    dialogOpen.value = true
    title.value = "修改商品"
}

/** 删除按钮操作 */
function handleDelete() {
    ElMessageBox.confirm('是否确认删除ID为"' + ids.value + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            ElMessage.success('批量删除操作，勾选的数据ID为:' + ids.value)
        })
        .catch(() => { })
}

/** 查看按钮操作 */
function handleView(row: Product) {
    getProduct(row.productId).then((res) => {
        currentProduct.value = res.data
        drawerOpen.value = true
    })
}
</script>

<style scoped>
.mb8 {
    margin-bottom: 8px;
}
</style>